package com.learn.queue.safety.blocking;

import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 生产者
 */
public class Producer implements Runnable {

    //是否在运行标志
    private volatile boolean isRunning = true;
    //阻塞队列
    private BlockingQueue queue;
    //生产者编号
    private int producerId;

    //自动更新的值
    private static AtomicInteger count = new AtomicInteger();
    private static final int DEFAULT_RANGE_FOR_SLEEP = 1000;
    private static final int TIME_OUT = 2;

    //构造函数
    public Producer(BlockingQueue queue) {
        this.queue = queue;
    }

    public Producer(BlockingQueue queue, int producerId) {
        this.queue = queue;
        this.producerId = producerId;
    }

    public void run() {
        String data;
        Random r = new Random();

        System.err.println("生产者-" + producerId + "-启动生产线程！" + Thread.currentThread().getName());
        try {
            while (isRunning) {
                System.out.println("生产者-" + producerId + "-正在生产数据...");
                Thread.sleep(r.nextInt(DEFAULT_RANGE_FOR_SLEEP));//取0~DEFAULT_RANGE_FOR_SLEEP值的一个随机数

                data = "data:" + count.incrementAndGet();//以原子方式将count当前值加1
                System.out.println("生产者-" + producerId + "-将数据：" + data + "放入队列...");

                //设定的等待时间为2s，如果超过2s还没加进去返回true
                if (!queue.offer(data, TIME_OUT, TimeUnit.SECONDS)) {
                    System.out.println("生产者-" + producerId + "-放入数据失败：" + data);
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
            Thread.currentThread().interrupt();
        } finally {
            System.err.println("生产者-" + producerId + "-退出生产者线程！" + Thread.currentThread().getName());
        }
    }

    public void stop() {
        isRunning = false;
    }

}
